<template>
  <div class="max-w-6xl mx-auto p-6">
    <!-- 加载状态 -->
    <div v-if="loading" class="flex justify-center items-center py-12">
      <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
      <span class="ml-2 text-gray-600">加载中...</span>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
      <div class="flex items-center">
        <svg class="w-5 h-5 text-red-400 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
        </svg>
        <span class="text-red-800">{{ error }}</span>
      </div>
    </div>

    <!-- 章节未启用 -->
    <div v-else-if="chapterConfig && !chapterConfig.isEnabled" class="bg-yellow-50 border border-yellow-200 rounded-lg p-6 text-center">
      <svg class="mx-auto h-12 w-12 text-yellow-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
      </svg>
      <h3 class="text-lg font-medium text-yellow-800 mb-2">章节暂未开放</h3>
      <p class="text-yellow-700">第{{ chapterNumber }}章内容暂时不可用，请稍后再试。</p>
    </div>

    <!-- 正常章节内容 -->
    <div v-else-if="chapterConfig">
      <!-- 章节标题 -->
      <div class="bg-white rounded-lg shadow-lg mb-6 p-6">
        <h1 class="text-2xl font-bold text-gray-900 mb-2">第{{ chapterConfig.chapterNumber }}章 {{ chapterConfig.title }}</h1>
        <p class="text-gray-600">{{ chapterConfig.description }}</p>
      </div>

      <!-- 导航栏 -->
      <div class="bg-white rounded-lg shadow-lg mb-6">
        <nav class="flex flex-wrap border-b border-gray-200 overflow-x-auto">
          <button 
            v-for="tab in availableTabs" 
            :key="tab.id" 
            @click="activeTab = tab.id" 
            :class="[
              'flex-1 min-w-0 py-3 px-2 sm:py-4 sm:px-4 md:px-6 text-center font-medium transition-colors duration-200 text-sm sm:text-base whitespace-nowrap flex items-center justify-center space-x-1 sm:space-x-2',
              activeTab === tab.id
                ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50'
                : 'text-gray-600 hover:text-gray-800 hover:bg-gray-50'
            ]"
          >
            <span>{{ tab.icon }}</span>
            <span class="block sm:hidden">{{ tab.name.length > 4 ? tab.name.substring(0, 4) + '...' : tab.name }}</span>
            <span class="hidden sm:block">{{ tab.name }}</span>
          </button>
        </nav>
      </div>

      <!-- Tab内容 -->
      <!-- 课件资料 Tab -->
      <div v-if="activeTab === 'materials' && chapterConfig.lecture">
        <MaterialsTab 
          :chapterPath="`/chap${chapterNumber.toString().padStart(2, '0')}/materials`" 
          :chapterNumber="chapterConfig.chapterNumber" 
          :materials="materialsConfig"
          :showChapterHighlights="true" 
        />
      </div>

      <!-- 视频内容 Tab -->
      <div v-if="activeTab === 'videos' && chapterConfig.video" class="bg-white rounded-lg shadow-lg">
        <VideosTab 
          :title="`第${chapterConfig.chapterNumber}章 ${chapterConfig.title}视频教程`"
          :mainVideos="videosConfig.mainVideos"
          :videoList="videosConfig.videoList"
        />
      </div>

      <!-- 示例内容 Tab -->
      <div v-if="activeTab === 'examples' && chapterConfig.examples" class="bg-white rounded-lg shadow-lg">
        <ExamplesGrid :examples="examples" :chapterName="'examples'" />
      </div>

      <!-- 实践课堂 Tab -->
      <PracticeTab v-if="activeTab === 'practice' && chapterConfig.practice" />

      <!-- 作业与任务 Tab -->
      <AssignmentTab v-if="activeTab === 'assignments' && chapterConfig.assignment" />

      <!-- 无内容提示 -->
      <div v-if="availableTabs.length === 0" class="bg-gray-50 border border-gray-200 rounded-lg p-6 text-center">
        <svg class="mx-auto h-12 w-12 text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
        </svg>
        <h3 class="text-lg font-medium text-gray-900 mb-2">暂无学习内容</h3>
        <p class="text-gray-600">该章节暂时没有配置学习材料，请联系老师。</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import ExamplesGrid from '@/components/ExamplesGrid.vue'
import MaterialsTab from '@/components/MaterialsTab.vue'
import VideosTab from '@/components/VideosTab.vue'
import PracticeTab from '@/components/PracticeTab.vue'
import AssignmentTab from '@/components/AssignmentTab.vue'

interface MaterialConfigType {
  url: string
  weight: number
  isRequired?: boolean
  allowDownload?: boolean
  duration?: number
  deadline?: string
  description?: string
}

interface ChapterConfig {
  id: number
  chapterNumber: number
  title: string
  description: string
  isEnabled: boolean
  lecture?: MaterialConfigType
  slides?: MaterialConfigType
  video?: MaterialConfigType
  examples?: MaterialConfigType
  practice?: MaterialConfigType
  assignment?: MaterialConfigType
  createdAt: string
  updatedAt: string
}

interface Example {
  id: string
  title: string
  description: string
  type: string
  difficulty: 'easy' | 'medium' | 'hard'
  fileName: string
  filePath: string
}

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

// 从路由参数获取章节号
const chapterNumber = computed(() => {
  const param = route.params.chapter
  return typeof param === 'string' ? parseInt(param) : 0
})

// 状态管理
const loading = ref(false)
const error = ref('')
const chapterConfig = ref<ChapterConfig | null>(null)
const activeTab = ref('materials')

// Tab 配置
const allTabs = [
  { id: 'materials', name: '课件资料', icon: '📚', configKey: 'lecture' },
  { id: 'videos', name: '视频内容', icon: '🎬', configKey: 'video' },
  { id: 'examples', name: '示例内容', icon: '💻', configKey: 'examples' },
  { id: 'practice', name: '实践课堂', icon: '🎨', configKey: 'practice' },
  { id: 'assignments', name: '作业与任务', icon: '📝', configKey: 'assignment' }
]

// 计算可用的标签页
const availableTabs = computed(() => {
  if (!chapterConfig.value) return []
  
  return allTabs.filter(tab => {
    const configKey = tab.configKey as keyof ChapterConfig
    const materialConfig = chapterConfig.value![configKey] as MaterialConfigType | undefined
    return materialConfig && materialConfig.url
  })
})

// 课件资料配置
const materialsConfig = computed(() => {
  if (!chapterConfig.value?.lecture) return []
  
  const materials = []
  
  if (chapterConfig.value.slides?.url) {
    materials.push({
      type: 'pdf',
      title: '本章课件',
      description: `${chapterConfig.value.title}相关课件`,
      icon: 'red',
      files: [chapterConfig.value.slides.url]
    })
  }
  
  if (chapterConfig.value.lecture?.url) {
    materials.push({
      type: 'docx',
      title: '本章讲义',
      description: `${chapterConfig.value.title}详细讲义`,
      icon: 'green',
      files: [chapterConfig.value.lecture.url]
    })
  }
  
  return materials
})

// 视频配置
const videosConfig = computed(() => {
  if (!chapterConfig.value?.video) {
    return { title: '', mainVideos: [], videoList: [] }
  }
  
  const config = chapterConfig.value
  const videoUrl = config.video?.url
  
  return {
    title: `第${config.chapterNumber}章 ${config.title}视频教程`,
    mainVideos: [
      {
        id: `chap${config.chapterNumber}-main1`,
        title: `${config.chapterNumber}.1 ${config.title}基础`,
        url: videoUrl,
        description: `${config.title}基础概念和语法`
      }
    ],
    videoList: [
      {
        id: `chap${config.chapterNumber}-1`,
        title: `${config.title}基础`,
        description: `${config.title}基本使用`,
        duration: config.video?.duration ? `${Math.floor(config.video.duration / 60)}:${(config.video.duration % 60).toString().padStart(2, '0')}` : '15:30',
        views: '1.2k',
        url: videoUrl
      }
    ]
  }
})

// 示例数据（这里可以根据实际需求从后端获取）
const examples = ref<Example[]>([])

// 加载章节配置
const loadChapterConfig = async () => {
  if (!chapterNumber.value) {
    error.value = '无效的章节号'
    return
  }
  
  loading.value = true
  error.value = ''
  
  try {
    const response = await fetch(`http://localhost:806/api/chapter-config/chapter/${chapterNumber.value}`, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    
    if (!response.ok) {
      if (response.status === 404) {
        throw new Error('章节配置不存在')
      }
      throw new Error('加载章节配置失败')
    }
    
    const data = await response.json()
    
    // 提取实际的章节配置数据
      const actualData = data.data;
      
      // 转换后端数据格式为前端期望的格式
      chapterConfig.value = {
        id: actualData.id,
        chapterNumber: actualData.chapterNumber,
        title: actualData.chapterTitle,
        description: actualData.chapterDescription,
        isEnabled: actualData.isActive,
      lecture: actualData.docxConfig && actualData.docxConfig.uploadedFiles && actualData.docxConfig.uploadedFiles.length > 0 ? {
        url: typeof actualData.docxConfig.uploadedFiles[0] === 'string' ? actualData.docxConfig.uploadedFiles[0] : actualData.docxConfig.uploadedFiles[0].url || actualData.docxConfig.uploadedFiles[0].path,
        weight: actualData.docxConfig.weight || 0,
        isRequired: actualData.docxConfig.isRequired || false,
        allowDownload: actualData.docxConfig.allowDownload || true,
        description: actualData.docxConfig.description || ''
      } : undefined,
      slides: actualData.pptxConfig && actualData.pptxConfig.uploadedFiles && actualData.pptxConfig.uploadedFiles.length > 0 ? {
        url: typeof actualData.pptxConfig.uploadedFiles[0] === 'string' ? actualData.pptxConfig.uploadedFiles[0] : actualData.pptxConfig.uploadedFiles[0].url || actualData.pptxConfig.uploadedFiles[0].path,
        weight: actualData.pptxConfig.weight || 0,
        isRequired: actualData.pptxConfig.isRequired || false,
        allowDownload: actualData.pptxConfig.allowDownload || true,
        description: actualData.pptxConfig.description || ''
      } : undefined,
      video: actualData.videosConfig && actualData.videosConfig.uploadedFiles && actualData.videosConfig.uploadedFiles.length > 0 ? {
        url: typeof actualData.videosConfig.uploadedFiles[0] === 'string' ? actualData.videosConfig.uploadedFiles[0] : actualData.videosConfig.uploadedFiles[0].url || actualData.videosConfig.uploadedFiles[0].path,
        weight: actualData.videosConfig.weight || 0,
        duration: actualData.videosConfig.duration,
        isRequired: actualData.videosConfig.isRequired || false,
        description: actualData.videosConfig.description || ''
      } : undefined,
      examples: actualData.examplesConfig && actualData.examplesConfig.uploadedFiles && actualData.examplesConfig.uploadedFiles.length > 0 ? {
        url: typeof actualData.examplesConfig.uploadedFiles[0] === 'string' ? actualData.examplesConfig.uploadedFiles[0] : actualData.examplesConfig.uploadedFiles[0].url || actualData.examplesConfig.uploadedFiles[0].path,
        weight: actualData.examplesConfig.weight || 0,
        isRequired: actualData.examplesConfig.isRequired || false,
        description: actualData.examplesConfig.description || ''
      } : undefined,
      practice: actualData.practiceConfig && actualData.practiceConfig.uploadedFiles && actualData.practiceConfig.uploadedFiles.length > 0 ? {
        url: typeof actualData.practiceConfig.uploadedFiles[0] === 'string' ? actualData.practiceConfig.uploadedFiles[0] : actualData.practiceConfig.uploadedFiles[0].url || actualData.practiceConfig.uploadedFiles[0].path,
        weight: actualData.practiceConfig.weight || 0,
        isRequired: actualData.practiceConfig.isRequired || false,
        description: actualData.practiceConfig.description || ''
      } : undefined,
      assignment: actualData.assignmentsConfig && actualData.assignmentsConfig.uploadedFiles && actualData.assignmentsConfig.uploadedFiles.length > 0 ? {
        url: typeof actualData.assignmentsConfig.uploadedFiles[0] === 'string' ? actualData.assignmentsConfig.uploadedFiles[0] : actualData.assignmentsConfig.uploadedFiles[0].url || actualData.assignmentsConfig.uploadedFiles[0].path,
        weight: actualData.assignmentsConfig.weight || 0,
        deadline: actualData.assignmentsConfig.deadline,
        isRequired: actualData.assignmentsConfig.isRequired || false,
        description: actualData.assignmentsConfig.description || ''
      } : undefined,
      createdAt: actualData.createdAt,
      updatedAt: actualData.updatedAt
    }
    
    // 处理examples数据，转换为ExamplesGrid期望的格式
    if (chapterConfig.value.examples && actualData.examplesConfig && actualData.examplesConfig.uploadedFiles) {
      examples.value = actualData.examplesConfig.uploadedFiles.map((file: any, index: number) => {
        const fileName = typeof file === 'string' ? file.split('/').pop() || file : (file.originalName || file.filename || `example-${index + 1}.html`)
        const filePath = typeof file === 'string' ? file : (file.url || file.path || file.filename)
        
        return {
          id: `example-${chapterNumber.value}-${index + 1}`,
          title: file.title || `第${chapterNumber.value}章示例${index + 1}`,
          description: file.description || actualData.examplesConfig.description || `第${chapterNumber.value}章的示例代码`,
          type: file.type || '示例代码',
          difficulty: (file.difficulty as 'easy' | 'medium' | 'hard') || 'easy',
          fileName: fileName,
          filePath: filePath
        }
      })
    } else {
      examples.value = []
    }
    
    console.log('处理后的examples数据:', examples.value)
    
    // 设置默认激活的标签页
    if (availableTabs.value.length > 0) {
      activeTab.value = availableTabs.value[0].id
    }
    
  } catch (err) {
    error.value = err instanceof Error ? err.message : '加载章节配置失败'
  } finally {
    loading.value = false
  }
}

// 处理路由参数以激活指定标签页
const handleRouteParams = () => {
  const tabParam = route.query.tab
  if (typeof tabParam === 'string' && availableTabs.value.some(tab => tab.id === tabParam)) {
    activeTab.value = tabParam
  }
}

// 监听路由查询参数变化
watch(
  () => route.query.tab,
  (newTab) => {
    if (typeof newTab === 'string' && availableTabs.value.some(tab => tab.id === newTab)) {
      activeTab.value = newTab
    }
  }
)

// 监听章节号变化
watch(
  () => chapterNumber.value,
  () => {
    loadChapterConfig()
  },
  { immediate: true }
)

// 监听可用标签页变化，确保当前激活的标签页有效
watch(
  () => availableTabs.value,
  (newTabs) => {
    if (newTabs.length > 0 && !newTabs.some(tab => tab.id === activeTab.value)) {
      activeTab.value = newTabs[0].id
    }
  }
)

// 生命周期钩子
onMounted(() => {
  handleRouteParams()
})
</script>

<style scoped>
/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>